import cv2
import numpy as np


def add_alpha_channel(img):
    # 为jpg图像添加alpha通道
    b_channel, g_channel, r_channel = cv2.split(img)  # 剥离jpg图像通道
    alpha_channel = np.ones(
        b_channel.shape, dtype=b_channel.dtype) * 255  # 创建Alpha通道
    img_new = cv2.merge(
        (b_channel, g_channel, r_channel, alpha_channel))  # 融合通道
    return img_new


img_jpg_path = '0.jpg'
img_jpg = cv2.imread(img_jpg_path, cv2.IMREAD_UNCHANGED)

if img_jpg.shape[2] == 3:
    img_jpg = add_alpha_channel(img_jpg)  # 检查是否有alpha通道，并添加
ff = img_jpg.shape[0]  # 获取尺寸
f = int(ff/2)

img_png_path = 'f.png'
img_png = cv2.imread(img_png_path, cv2.IMREAD_UNCHANGED)
img_png = cv2.resize(img_png, (f, f), interpolation=cv2.INTER_AREA)  # 调整大小

alpha_png = img_png[0:f, 0:f, 3] / 255.0
alpha_jpg = 1 - alpha_png
for c in range(0, 3):
    img_jpg[0:f, 0:f, c] = (
        (alpha_jpg*img_jpg[0:f, 0:f, c]) + (alpha_png*img_png[0:f, 0:f, c]))
cv2.imwrite('res.jpg', img_jpg)
cv2.imshow('img_jpg', img_jpg)
cv2.waitKey()
cv2.destroyAllWindows()